package com.example.linxilite.ui.login

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.linxilite.network.RetrofitClient
import com.example.linxilite.network.api.UserApi
import com.example.linxilite.network.model.LoginRequest
import com.example.linxilite.network.model.LoginResponse
import kotlinx.coroutines.launch

class LoginViewModel : ViewModel() {
    private val userApi = RetrofitClient.instance.create(UserApi::class.java)

    var loginState by mutableStateOf<LoginResponse?>(null)
    var errorMessage by mutableStateOf<String?>(null)

    fun login(phone: String, password: String) {
        viewModelScope.launch {
            try {
                val response = userApi.login(LoginRequest(phone, password))
                if (response.isSuccessful) {
                    loginState = response.body()
                    // 保存 JWT 到 DataStore
                } else {
                    errorMessage = "登录失败：${response.code()}"
                }
            } catch (e: Exception) {
                errorMessage = "网络错误：${e.message}"
            }
        }
    }
}
